import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * The ChatLog - Chris Hansen's only weak point
 */
public class ChatLog  extends Actor implements Runnable
{
    retroWorld theWorld;
    Simon simon;
    Health health;
    
    private int hitPoints = 10;
    
    private boolean alive;
    private boolean invincible;
    private long timeStartInvincible;
    private Chris chris;
    BossHealth healthBar = new BossHealth(hitPoints);
    
    private volatile Thread t;

    /** Constructor, create a new ChatLog and link it with Chris
     * 
     */
    public ChatLog(Chris c)
    {
        alive = true;
        invincible = false;
        chris=c;
    }
    
    public void run()
    {
        while(alive)
        {
            checkCollision();
            checkInvincible();            
        }
    }
    
    public void addedToWorld(World world)
    {
        theWorld = (retroWorld)world;
        simon = theWorld.getSimon();
        health = theWorld.getHealth();
        
        theWorld.addObject(healthBar, (theWorld.worldWidth - 50), (theWorld.worldHeight - 300));
        t = new Thread(this);
        t.start();       
    }
    
    private synchronized void checkCollision()
    {
        if (intersects(simon))
        {
            if (simon.isCurrentlyWhipping()){
                if (!invincible)
                {
                    invincible = true;
                    takeHit();
                    
                    timeStartInvincible=System.currentTimeMillis();
                }
                return;
            }
            
        }
    }
    
    private void removeFromWorld()
    {
        try {
        
        theWorld.addObject(new Explosion(), getX(), getY());
        theWorld.addObject(new EndingScreen(), theWorld.worldWidth/2, theWorld.worldHeight/2);
        t.sleep(1000);
        
        chris.removeFromWorld();
        
        alive=false;
        theWorld.removeObject(this);
        
        t=null;
        
        } catch (InterruptedException e) {}
    }
    
    /** Take Damage from Simon's whip attack
     * 
     */
    private void takeHit()
    {
         hitPoints--;
        healthBar.takeDamage();
       
       
        if (hitPoints <= 0)
            removeFromWorld();
    }
    
    /** Function to make Chris Hansen invincible for 3 seconds between hits
     * 
     */
    private void checkInvincible(){
        if(!invincible)
            return;
        
        long time=System.currentTimeMillis();
        
        //Invincible for 3 seconds
        if((time-timeStartInvincible) > 5000)
            invincible=false;
        
    }
}
